package com.sc.admin.common.util;

import com.alibaba.excel.EasyExcel;
import com.sc.admin.plugin.easyexcel.MyAnalysisEventListener;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel 工具类
 *
 * @author shen chen
 * @since 2023/03/01
 */
public class ExcelUtils {

    public static <T> String importExcel(InputStream is, Class<?> clazz, MyAnalysisEventListener<T> listener) {
        EasyExcel.read(is, clazz, listener).sheet().doRead();
        return listener.getMsg();
    }

    /**
     *  导出Excel
     * @param response response
     * @param clazz 导出类对象
     * @param exportUserList 导出的数据集
     * @param fileName 导出的文件名
     */
    public static void export(HttpServletResponse response, Class<?> clazz, List<?> exportUserList, String fileName) throws IOException {
        fileName = fileName + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        EasyExcel.write(response.getOutputStream(), clazz).sheet("用户列表").doWrite(exportUserList);
    }
}
